// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
namespace kumo::pollux::exec {
    template<typename T>
    bool VectorHasher::tryMapToRangeSimd(
        const T *values,
        const SelectivityVector &rows,
        uint64_t *result) {
        bool inRange = true;
        auto allLow = ksimd::broadcast<T>(min_);
        auto allHigh = ksimd::broadcast<T>(max_);
        auto allOne = ksimd::broadcast<T>(1);
        vector_size_t row = rows.begin();
        constexpr int kWidth = ksimd::batch<T>::size;
        for (; row + kWidth <= rows.end(); row += kWidth) {
            auto data = ksimd::load_unaligned(values + row);
            int32_t gtMax = simd::toBitMask(data > allHigh);
            int32_t ltMin = simd::toBitMask(data < allLow);
            // value - (low - 1) doesn't work when low is the lowest possible (e.g.
            // std::numeric_limits<int64_t>::min())
            if constexpr (sizeof(T) == sizeof(uint64_t)) {
                (data - allLow + allOne).store_unaligned(result + row);
            }
            if ((gtMax | ltMin) != 0) {
                inRange = false;
                break;
            }
        }

        if (inRange) {
            for (; row < rows.end(); row++) {
                auto value = values[row];
                if (value > max_ || value < min_) {
                    inRange = false;
                    break;
                }
                if constexpr (sizeof(T) == sizeof(uint64_t)) {
                    result[row] = value - min_ + 1;
                }
            }
            if constexpr (sizeof(T) != sizeof(uint64_t)) {
                for (row = rows.begin(); row < rows.end(); row++) {
                    result[row] = values[row] - min_ + 1;
                }
            }
        }
        return inRange;
    }
} // namespace kumo::pollux::exec
